package com.atguigu.lease.web.admin.custom.interceptor;



import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: AuthenticationInterceptor
 * Package: com.atguigu.lease.web.admin.custom.interceptor
 * Description:
 * 校验JWT的拦截器 : 认证拦截器 , 拦截器中校验token是否合法，是否过期，是否被篡改
 *
 * @Autor: xvyy
 * @Create: 2024/11/20 - 20:55
 * @Version: v1.0
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //todo   获取请求头中的token
        String token = request.getHeader("access_token");

        //todo   解析token
        Claims claims = JwtUtil.parseToken(token);

        //todo   获取token中的用户id和用户名，并封装到LoginUser对象中，并放入ThreadLocal中
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUser loginUser = new LoginUser(userId, username);
        LoginUserContext.setLoginUser(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
